<template>
  <div class="box">
    <!--    部门列表-->
    <div class="box_right">
      <ProTable
        ref="proTable"
        :columns="columns"
        :data-callback="dataCallback"
        :init-param="initParam"
        :request-api="getTableList"
        :selection="true"
        :toolButton="false"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <div class="header-button-lf">
            <el-button :icon="CirclePlus" type="primary" @click="openDrawer('新增')">新增</el-button>
          </div>


          <div class="header-button-ri">
            <el-input
              v-model="keywords"
              class="inline-block"
              placeholder="请输入部门名称检索"
              style="width: 304px"></el-input>
            <el-button icon="Search" type="primary" @click="handleSearch">查询</el-button>
            <el-button icon="Search" type="primary" @click="handleSearch">重置</el-button>
          </div>
        </template>
        <!-- Expand -->
        <template #expand="scope">
          {{ scope.row }}
        </template>
        <!-- 创建时间自定义表头 -->
        <template #dateHeader="scope">
        <span class="inline-block">
          <span class="flx-align-center">
            <span>{{ scope.column.label }}</span>
            <span class="flx-align-center ml-10">
              <el-icon @click.stop="handleClickCalendar"><Calendar/></el-icon>
              <el-date-picker
                ref="timePick"
                v-model="times"
                class="time-pick"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="开始日期"
                type="daterange"
                value-format="YYYY-MM-DD"
                @change="changeTimePick"
              >
              </el-date-picker>
            </span>
          </span>
        </span>
        </template>
        <!-- 自定义内容 -->
        <template #createTime="scope">
          <el-button link type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
            {{ scope.row.createTime }}
          </el-button>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <a style="color: #3370FF;margin-right: 12px" @click="openDrawer('下级新增', scope.row)">新增</a>
          <a style="color: #3370FF;margin-right: 12px" @click="openDrawer('编辑', scope.row)">编辑</a>
          <a style="color: #FF0000;" @click="deleteAccount(scope.row)">删除</a>
        </template>
      </ProTable>
      <!--      新增编辑用户弹窗-->
      <addUesrs v-if="addUesrsList.visble" :datas="addUesrsList" @back="addUesrsList.visble=false"/>

    </div>
  </div>
</template>
<script lang="tsx" setup>
import {reactive, ref} from "vue";
import {User} from "@/api/interface";
import {useHandleData} from "@/hooks/useHandleData";
import {useAuthButtons} from "@/hooks/useAuthButtons";
import {ElMessage} from "element-plus";
import addUesrs from "./model/addDepartments.vue";
import {ColumnProps, ProTableInstance} from "@/components/ProTable/interface";
import {Calendar, CirclePlus} from "@element-plus/icons-vue";
import {changeUserStatus, deleteUser, getUserList, resetUserPassWord} from "@/api/modules/user";
import ProTable from "@/components/ProTable/index.vue";

// 新增编辑部门
const addUesrsList = ref({
  visble: false,
  forms: {
    title: '',
  }
})

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  type: 1,
  keywords: ""
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.list,
    total: data.total
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  delete newParams.createTime;
  return getUserList(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const {BUTTONS} = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
// const headerRender = (scope: HeaderRenderScope<User.ResUserList>) => {
//   return (
//     <span class="inline-block">
//       <span class="flx-align-center">
//         {scope.column.label}
//         <el-icon
//           class="ml-10"
//           onClick={e => {
//             e.stopPropagation();
//           }}
//         >
//           <Calendar />
//         </el-icon>
//       </span>
//     </span>
//   );
// };

// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  {
    prop: "name",
    label: "用户账号",
    minWidth: 178
  },


  {
    minWidth: 146,
    prop: "address",
    label: "部门类型",
    // 字典数据（本地数据）
    // enum: genderType,
    // 字典请求不带参数
    // enum: getUserGender,
    // // 字典请求携带参数
    // // enum: () => getUserGender({ id: 1 }),
    // fieldNames: {label: "genderLabel", value: "genderValue"},

    // 是否多选  默认多选
    filterMultiple: false,
    filters: [
      {text: "男", value: "1"},
      {text: "女", value: "2"}
    ],
    filterMethod: (value, row) => {
      return row.gender == value;
    }
  },

  {
    prop: "date",
    label: "创建时间",
    sortable: true,
    minWidth: 128
  },
  {prop: "operation", label: "操作", fixed: "right", minWidth: 80}
]);
// 重置用户密码
const resetPass = async (ids) => {
  await useHandleData(resetUserPassWord, {id: ids}, `是否确定重置密码`);
  proTable.value?.getTableList();
};

// 删除
const deleteAccount = async (params: User.ResUserList) => {
  await useHandleData(deleteUser, {id: [params.id]}, `删除【${params.username}】用户`);
  proTable.value?.getTableList();
};

// 批量删除
const batchDelete = async (id: string[]) => {
  await useHandleData(deleteUser, {id}, "删除所选用户信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};


// 开关启用
const changeStatus = async (row: User.ResUserList) => {
  await useHandleData(changeUserStatus, {id: row.id, status: row.status == 1 ? 0 : 1}, `切换【${row.username}】用户状态`);
  proTable.value?.getTableList();
};

const openDrawer = (title, row) => {
  addUesrsList.value.visble = true
  addUesrsList.value.forms.title = title
};

// 搜索关键词
const keywords = ref("");

// 选择时间
const times = ref([]);
const timePick = ref();
const handleClickCalendar = () => {
  timePick.value.focus();
};

const changeTimePick = () => {
  console.log(times.value);
};
// 查询
const handleSearch = () => {
  initParam.keywords = keywords.value;
};


const input = ref("")
//  查询部门
const departmentSearch = () => {
  console.log('部门搜索')
}

interface Tree {
  label: string
  children?: Tree[]
}

const handleNodeClick = (data: Tree) => {
  console.log(data)
}

const data: Tree[] = [
  {
    label: '菩勤责任公司',
    children: [
      {
        label: '菩勤枣庄',
        children: [
          {
            label: '商标',
          },
        ],
      },
    ],
  },

]

const defaultProps = {
  children: 'children',
  label: 'label',
}
</script>
<style lang="scss" scoped>
:deep(.el-tree-node:focus > .el-tree-node__content) {
  background-color: rgba(31, 97, 243, 0.10);
  color: rgba(51, 112, 255, 1);
}


.box {
  display: flex;
  width: 100%;


  .box_right {
    padding: 12px;
    min-width: 600px;
    flex: 1;
    background: #ffffff;
    border-radius: 4px 4px 4px 4px;
  }
}
</style>
